package com.weifly.egp.service.config;

import com.weifly.egp.service.monitor.StockInfo;
import org.apache.commons.io.IOUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 读取网格魔方的配置
 *
 * Created by weijianxin on 2018/8/20.
 */
public class GridConfigServiceImpl implements GridConfigService {

    private Logger logger = LoggerFactory.getLogger(GridConfigServiceImpl.class);

    private File configFile; // 配置文件
    private String apiUrl = null;  // 网格魔方交易地址

    public void setConfigFile(File configFile) {
        this.configFile = configFile;
    }

    public List<StockInfo> parseConfig() {
        List<StockInfo> stockList = new ArrayList<>();

        SAXReader reader = new SAXReader();
        try{
            Document document = reader.read(this.configFile);
            Element rootEle = document.getRootElement();

            Element apiUrlEle = rootEle.element("apiUrl");
            if(apiUrlEle!=null){
                this.apiUrl = apiUrlEle.getText();
            }

            List<Element> tradeEleList = rootEle.elements("trade");
            if(tradeEleList!=null){
                for(Element tradeEle : tradeEleList){
                    StockInfo stockInfo = new StockInfo();
                    stockInfo.setStockCode(tradeEle.element("stockCode").getText());
                    stockInfo.setStockName(tradeEle.element("stockName").getText());
                    stockInfo.setCreditBuy("true".equals(tradeEle.element("creditBuy").getText()));
                    stockInfo.setBasePrice(Double.valueOf(tradeEle.element("basePrice").getText()));
                    stockInfo.setGridPrice(Double.valueOf(tradeEle.element("gridPrice").getText()));
                    stockInfo.setTradeUnit(Integer.valueOf(tradeEle.element("tradeUnit").getText()));

                    Element gridPriceListEle = tradeEle.element("gridPriceList");
                    if(gridPriceListEle!=null){
                        List<Element> priceEleList = gridPriceListEle.elements("price");
                        for(Element priceEle : priceEleList){
                            stockInfo.getGridPriceList().add(Double.valueOf(priceEle.getText()));
                        }
                    }

                    stockList.add(stockInfo);
                    logger.info("加载股票："+stockInfo.getStockCode());
                }
            }

            return stockList;
        }catch(DocumentException e){
            logger.error("", e);
            throw new RuntimeException(e);
        }
    }

    public String getApiUrl() {
        return this.apiUrl;
    }

    public void saveConfig(List<StockInfo> stockList) {
        DocumentFactory factory = DocumentFactory.getInstance();

        Document document = factory.createDocument();
        document.setXMLEncoding("UTF8");

        Element rootEle = factory.createElement("config");
        document.setRootElement(rootEle);

        Element apiUrl = factory.createElement("apiUrl");
        apiUrl.setText(this.apiUrl);
        rootEle.add(apiUrl);

        if(stockList!=null && stockList.size()>0){
            for(StockInfo stockInfo : stockList){
                Element tradeEle = factory.createElement("trade");

                Element stockCodeEle = factory.createElement("stockCode");
                stockCodeEle.setText(stockInfo.getStockCode());
                tradeEle.add(stockCodeEle);

                Element stockNameEle = factory.createElement("stockName");
                stockNameEle.setText(stockInfo.getStockName());
                tradeEle.add(stockNameEle);

                Element creditBuyEle = factory.createElement("creditBuy");
                creditBuyEle.setText(stockInfo.isCreditBuy()?"true":"false");
                tradeEle.add(creditBuyEle);

                Element basePriceEle = factory.createElement("basePrice");
                basePriceEle.setText(stockInfo.getBasePrice().toString());
                tradeEle.add(basePriceEle);

                Element gridPriceEle = factory.createElement("gridPrice");
                gridPriceEle.setText(stockInfo.getGridPrice().toString());
                tradeEle.add(gridPriceEle);

                Element tradeUnitEle = factory.createElement("tradeUnit");
                tradeUnitEle.setText(stockInfo.getTradeUnit().toString());
                tradeEle.add(tradeUnitEle);

                Element gridPriceListEle = factory.createElement("gridPriceList");
                for(Double price : stockInfo.getGridPriceList()){
                    Element priceEle = factory.createElement("price");
                    priceEle.setText(price.toString());
                    gridPriceListEle.add(priceEle);
                }
                tradeEle.add(gridPriceListEle);

                rootEle.add(tradeEle);
            }
        }

        FileOutputStream output = null;
        try{
            output = new FileOutputStream(this.configFile);
            OutputFormat format = new OutputFormat("  ", true, "UTF8");
            XMLWriter writer = new XMLWriter(output, format);
            writer.write(document);
            writer.close();
        }catch(IOException e){
            throw new RuntimeException(e);
        }finally {
            IOUtils.closeQuietly(output);
        }
    }
}
